<template>
  <div class="app-container">
    <el-descriptions title="商品信息" :column="4" size="small" border>
      <el-descriptions-item label="商品编码">{{ mainInfo.gNumber }}</el-descriptions-item>
      <el-descriptions-item label="商品名称">{{ mainInfo.goodsName }}</el-descriptions-item>
      <el-descriptions-item label="商品品牌">{{ mainInfo.brandName }}</el-descriptions-item>
      <el-descriptions-item label="商品类型">{{ mainInfo.typeName }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <dict-tag :options="dict.type.sys_goods_sj_status" :value="mainInfo.status"/>
      </el-descriptions-item>
      <el-descriptions-item label="备注"    >{{ mainInfo.remark }}</el-descriptions-item>
    </el-descriptions>
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="商品属性" name="config">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="config.loading"
              @click="handleConfigAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleConfigAddLine"
            >新增行</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="config.multiple"
              @click="handleConfigDel"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-finished"
              size="mini"
              :disabled="config.loading"
              @click="handleSaveConfig"
            >保存</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              icon="el-icon-view"
              size="mini"
              @click="handleGetAssConfig"
              style="background-color: floralwhite;"
            >关联属性</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="handleRefreshConfig"
            >刷新</el-button>
          </el-col>
          <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
        <el-table
          border
          ref="dragTable"
          v-loading="config.loading"
          :data="configList"
          row-key="gConfigId"
          :row-class-name="rowConfigIndex"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" prop="index" width="50" align="center" class-name="allowDrag" />
          <el-table-column label="属性" prop="attrId" align="center" >
            <template slot-scope="scope">
              <el-cascader
                v-model="scope.row.attr"
                :options="options.attrOptions"
                :show-all-levels="false"
                filter clearable
                @change="handleAttrIdChange(scope.row, ...arguments)"
                placeholder="请选择商品属性"
              ></el-cascader>
              <!-- :props="{ checkStrictly: true }" -->
            </template>
          </el-table-column>
          <el-table-column label="属性名称" prop="attrName" align="center" :render-header="renderHeader" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.attrName" placeholder="属性名称"/>
            </template>
          </el-table-column>
          <el-table-column label="属性值" prop="valueId" align="center" :render-header="renderHeader" >
            <template slot-scope="scope">
              <!-- {{ scope.row }} -->
              <el-select
                v-if="scope.row.multiple"
                v-model="scope.row.valueIds"
                allow-create clearable filterable multiple collapse-tags
                placeholder="属性值"
                @change="handleAttrValChange(scope.row, $event)" >
                <el-option
                  v-for="op in scope.row.attrValOptions"
                  :key="op.valueId+''"
                  :label="op.valueLabel+' ['+op.valueId+']'"
                  :value="op.valueId+''"
                />
              </el-select>
              <el-select
                v-else
                v-model="scope.row.valueId"
                allow-create clearable filterable
                placeholder="属性值"
                @change="handleAttrValChange(scope.row, $event)" >
                <el-option
                  v-for="op in scope.row.attrValOptions"
                  :key="op.valueId+''"
                  :label="op.valueLabel+' ['+op.valueId+']'"
                  :value="op.valueId+''"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="属性值" prop="valueName" align="center" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.valueName" placeholder="属性值" disabled />
            </template>
          </el-table-column>
          <el-table-column label="自定义属性值" prop="configVal" align="center" :render-header="renderHeader" >
            <template slot-scope="scope">
              <el-input v-model="scope.row.configVal" clearable placeholder="自定义属性值"/>
            </template>
          </el-table-column>
          <!-- <el-table-column label="检索标志" prop="isSrchcond" width="80" align="center" >
              <template slot-scope="scope">
                  <el-select v-model="scope.row.isSrchcond" placeholder="检索标志">
                    <el-option
                      v-for="dict in dict.type.sys_yes_no"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
              </template>
          </el-table-column> -->
          <el-table-column label="状态" prop="delFlag" width="100" align="center" >
            <template slot-scope="scope">
<!--              <el-select v-model="scope.row.delFlag" placeholder="状态">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>-->
              <el-switch
                v-model="scope.row.delFlag"
                active-value="0"
                inactive-value="1"
              ></el-switch>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="image">
        <el-form :model="queryParams" ref="queryForm" size="small" v-show="image.showSearch" :inline="true" label-width="68px">
          <el-form-item label="类型" prop="imgType">
            <el-select v-model="queryParams.imgType" placeholder="请选择图片类型" clearable>
              <el-option
                v-for="dict in dict.type.sys_goods_img_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="delFlag">
            <el-select v-model="queryParams.delFlag" placeholder="请选择图片状态" clearable>
              <el-option
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleImageAdd"
              v-hasPermi="['goods:image:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="image.single"
              @click="handleImageUpdate"
              v-hasPermi="['goods:image:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="image.multiple"
              @click="handleImageDelete"
              v-hasPermi="['goods:image:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="image.showSearch" @queryTable="getImgList" ></right-toolbar>
        </el-row>

        <el-table border stripe v-loading="image.loading" :data="imageList" @selection-change="handleImgSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="图片ID" align="center" prop="imgId" width="80" />
          <el-table-column label="图片类型" align="center" prop="imgType" width="100" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_goods_img_type" :value="scope.row.imgType"/>
            </template>
          </el-table-column>
          <el-table-column label="顺序" align="center" prop="orderNum" width="60" />
          <el-table-column label="图片名称" align="center" prop="imgName" :show-overflow-tooltip="true" />
          <el-table-column label="图片地址" align="center" prop="imgPath" :show-overflow-tooltip="true" />
          <el-table-column label="图片" align="center" prop="imgPath" style="height: 50px;" >
            <template slot-scope="scope">
              <el-image v-if="isHttpUrl(scope.row.imgPath)" :src="scope.row.imgPath+'?imageView2/0/w/50'" :preview-src-list="scope.row.previewSrc"
                        style="width: auto; height: 40px;" fit="cover" />
              <el-image v-else :src="image.imgServe+scope.row.imgPath" :preview-src-list="scope.row.previewSrc"
                        style="width: auto; height: 40px;" fit="cover" />
            </template>
          </el-table-column>
          <el-table-column label="操作人" align="center" prop="updateBy" />
          <el-table-column label="操作时间" align="center" prop="updateTime" width="160" />
          <el-table-column label="状态" align="center" prop="delFlag" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.delFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleImageUpdate(scope.row)"
                v-hasPermi="['goods:image:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleImageDelete(scope.row)"
                style="color: #f56c6c"
                v-hasPermi="['goods:image:edit']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getImgList"
        />
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="desc">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="config.loading"
              @click="handleDescAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-refresh"
              size="mini"
              @click="handleRefreshDesc"
            >刷新</el-button>
          </el-col>
        </el-row>
        <el-table
          border
          v-loading="desc.loading"
          :data="descList"
          row-key="descId"
        >
          <!-- @selection-change="handleSelectionChange" -->
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="ID" prop="descId" align="center" />
<!--          <el-table-column label="内容" prop="content" align="center" width="250" :show-overflow-tooltip="true" />-->
          <el-table-column label="备注" prop="remark" align="center" />
          <el-table-column label="创建者" prop="createBy" align="center" />
          <el-table-column label="创建时间" prop="createTime" align="center" />
          <el-table-column label="操作者" prop="updateBy" align="center" />
          <el-table-column label="操作时间" prop="updateTime" align="center" />
          <el-table-column label="状态" prop="delFlag" width="100" align="center" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.delFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleDescUpdate(scope.row)"
                v-hasPermi="['goods:desc:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDescDelete(scope.row)"
                style="color: #f56c6c"
                v-hasPermi="['goods:desc:edit']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>
    </el-tabs>

    <!-- 配置属性 -->
    <el-dialog :title="dialogInfo.configTitle" :visible.sync="dialogInfo.configOpen" :close-on-click-modal="false"
               width="1000px" append-to-body >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="config.loading"
            @click="handleAddAttr"
          >添加</el-button>
        </el-col>
      </el-row>

      <el-table
        border stripe
        :data="dialogInfo.attrList"
        @selection-change="handleAttrSelectionChange"
        :row-class-name="rowConfigIndex"
        row-key="attrId" >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="属性编码" prop="attrCode" align="center" />
        <el-table-column label="属性名称" prop="attrName" align="center" />
        <el-table-column label="属性值单位" align="center" prop="valueUnit">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_goods_attr_unit" :value="scope.row.valueUnit"/>
          </template>
        </el-table-column>
        <el-table-column label="是否多选" align="center" prop="valueRadio">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.valueRadio"/>
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="updateBy" />
        <el-table-column label="操作时间" align="center" prop="updateTime" width="160" />
        <el-table-column label="状态" align="center" prop="delFlag">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.delFlag"/>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 图片新增或修改 -->
    <el-dialog :title="dialogInfo.imageTitle" :visible.sync="dialogInfo.imageOpen" :close-on-click-modal="false"
               width="1000px" append-to-body>
      <el-form ref="imageForm" :model="image.form" :rules="image.rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编码" prop="gNumber">
              <el-input v-model="image.form.gNumber" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input v-model="image.form.goodsName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="图片类型" prop="imgType">
              <el-select v-model="image.form.imgType" placeholder="请选择图片类型" :style="{width: '100%'}">
                <el-option
                  v-for="dict in dict.type.sys_goods_img_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input v-model="image.form.orderNum" type="number" placeholder="请输入显示顺序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片名称" prop="imgName">
          <el-input v-model="image.form.imgName" placeholder="请输入图片名称" />
        </el-form-item>
        <el-form-item label="图片">
          <el-button @click="openSelectImage" type="success" plain>选择已上传图片</el-button>
        </el-form-item>
        <el-form-item label="" prop="imgPath">
          <image-upload ref="uploadImage" v-model="image.form.imgPath" :auto-upload="false"
                        :limit="uploadLimit(image.form)" @success="handleImageSuccess" />
        </el-form-item>
        <el-form-item label="状态" prop="delFlag">
          <el-radio-group v-model="image.form.delFlag">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="image.form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="imageCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情新增或修改 -->
    <el-dialog :title="dialogInfo.descTitle" :visible.sync="dialogInfo.descOpen" :close-on-click-modal="false"
               width="1000px" append-to-body>
      <el-form ref="descForm" :modal="desc.form" label-width="80px" >
        <el-form-item label="商品编码" prop="gNumber">
          <el-input v-model="desc.form.gNumber" disabled />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <editor v-model="desc.form.content" :min-height="250"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="desc.form.remark" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="delFlag">
          <el-radio-group v-model="desc.form.delFlag">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="descSubmitForm">确 定</el-button>
        <el-button @click="descCancel">取 消</el-button>
      </div>
    </el-dialog>

    <select-image ref="select" :params="{ 'gNumber': gNumber, 'limit': 10 }" @ok="handleSelectOk" />
  </div>
</template>

<script>
import { getMainByGNumber } from "@/api/goods/main";
import { listConfig, addConfig, getAssConfig } from "@/api/goods/config";
import { getImg, addImg, updateImg, delImg, findMaxOrderNum, listImg } from '@/api/goods/image'
import { getAttr, treeSelect as optionAttrSelect, findAttrsWithoutConfig } from "@/api/goods/attr";
import { listDesc, getDesc, addDesc, updateDesc, delDesc } from "@/api/goods/desc";
import selectImage from '@/views/goods/images/components/selectImage.vue'
import Sortable from 'sortablejs'

export default {
  name: "GoodsConfigEdit",
  dicts: ['sys_normal_disable', 'sys_goods_sj_status', 'sys_yes_no', 'sys_goods_attr_unit', 'sys_goods_img_type'],
  components: {
    selectImage
  },
  data() {
    return {
      // 商品 id
      gNumber: null,
      // 选中tab页面
      activeName: "config",
      config: {
        // 是否等待
        loading: false,
        // 选中数组
        indexs: [],
        // 非多个禁用
        multiple: true,
        // 非单个禁用
        single: true,
      },
      image: {
        imgServe: process.env.VUE_APP_BASE_API,
        // 是否等待
        loading: false,
        // 展示检索条件
        showSearch: false,
        // 选中数组
        ids: [],
        // 非多个禁用
        multiple: true,
        // 非单个禁用
        single: true,
        //
        form: {},
        //
        rules: {
          goodsId: [
            { required: true, message: "商品不能为空", trigger: "blur" }
          ],
          imgType: [
            { required: true, message: "图片类型不能为空", trigger: "blur" }
          ],
        },
      },
      desc: {
        loading: false,
        form: {},
      },
      mainInfo: {},
      configList: [],
      selectedList: [],
      imageList: [],
      descList: [],
      options: {
        attrOptions: []
      },
      // 弹出层信息
      dialogInfo: {
        // 弹出层标题
        configTitle: "",
        imageTitle: "",
        descTitle: "",
        // 是否显示弹出层
        configOpen: false,
        imageOpen: false,
        descOpen: false,
        // 数据
        attrList: [],
        // 选中的属性数据
        selectAttrList: [],
      },
      // 图片信息查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gNumber: null,
        imgType: null,
        delFlag: null,
      },
      total: 0,

    }
  },
  created() {
    const gNumber = this.$route.params && this.$route.params.gNumber;
    const type = this.$route.query && this.$route.query.type;
    this.queryParams.gNumber = gNumber;
    this.gNumber = gNumber;
    if (type) {
      this.activeName = type;
    }
    this.getMain();
    this.getConfigInfos();
    this.getImgList();
    this.getDesc();
  },
  watch: {
    // 加载 tab 页
    '$route.query'(newQuery, oldQuery) {
      if (newQuery) {
        this.activeName = newQuery.type;
      }
    }
  },
  mounted() {
    // 实现行拖拽
    const el = this.$refs.dragTable.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
    const sortable = Sortable.create(el, {
      handle: ".allowDrag",
      onEnd: evt => {
        const targetRow = this.configList.splice(evt.oldIndex, 1)[0];
        this.configList.splice(evt.newIndex, 0, targetRow);
        for (let index in this.configList) {
          this.configList[index].sort = parseInt(index) + 1;
        }
      }
    });
  },
  methods: {
    /** 查询商品属性下拉树结构 */
    async getAttrTreeselect() {
      let list = []
      await optionAttrSelect().then(response => {
        // this.options.attrOptions = this.handleTree(response.data, "attrId", "parentId");
        list = response.data;
      });
      this.generateAttrOptions(list);
      this.options.attrOptions = list;
    },
    /** 查询商品主体信息 */
    getMain() {
      const gNumber = this.gNumber;
      getMainByGNumber(gNumber).then(res => {
        this.mainInfo = res.data;
      })
    },
    /** 属性下拉列表转换 */
    generateAttrOptions(options) {
      if (options) {
        options.forEach(item => {
          if (item.object && item.object.valueUnit) {
            item.label = item.label + '【' + item.object.valueUnit + '】'
          }
          if (item.children && item.children.length > 0) {
            this.generateAttrOptions(item.children);
          }
        })
      }
    },
    /** 查询商品属性配置信息 */
    async getConfigInfos(gNumber) {
      if (!gNumber) {
        gNumber = this.gNumber;
      }
      this.config.loading = true;
      const param = { 'gNumber': gNumber};
      let dataList = [];

      await this.getAttrTreeselect();
      await listConfig(param).then(res => {
        dataList = res.data;
      })
      if (dataList && dataList.length > 0) {
        for (let i = 0; i < dataList?.length; i++) {
          if (dataList[i].attrId) {
            let item = [];
            let multiple = false;
            await getAttr(dataList[i].attrId).then(r => {
              item = r.data.sprdGoodsAttrValList;
              multiple = r.data.valueRadio == 'Y'
            })
            dataList[i].multiple = multiple
            dataList[i].attrValOptions = item
            dataList[i].attr = this.getCascaderVal(this.options.attrOptions, dataList[i].attrId);
            if (multiple && dataList[i].valueId) {
              dataList[i].valueIds = dataList[i].valueId.split(',')
            }
          } else {
            dataList[i].attrValOptions = [];
          }
        }
      }
      this.configList = dataList;
      this.config.loading = false;
    },
    /** 通过id 转换为 cascader 值 */
    getCascaderVal(options, value) {
      let result = [];
      if (options && value) {
        options.some(o => {
          if (o.id == value) {
            result = [o.value];
            return true;
          }
          if (o.children) {
            let bo = false;
            o.children.some(c => {
              if (c.id == value) {
                result = [o.value, c.value];
                bo = true;
                return true;
              }
            })
            if (bo) {
              return bo;
            }
          }
        })
      }
      return result;
    },
    /** 获取 cascader 值的末位 id */
    getLastValueByArray(arr) {
      if (arr && arr.length > 0) {
        return arr[arr.length -1];
      }
      return null;
    },
    /** 商品属性值序号 */
    rowConfigIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
      let rowClass = '';
      if (row.gConfigId) {
        rowClass += ' info-row'
      }
      if (this.mainInfo.assort && this.mainInfo.assort.split(',').includes(row.attrId+'')) {
        rowClass += ' required'
      }
      return rowClass;
    },
    /** 属性下拉列表修改事件 */
    handleAttrIdChange(row, val) {
      row.valueId = null;
      row.valueName = null;
      row.attrValOptions = [];
      let attrId = this.getLastValueByArray(val);
      if (attrId) {
        row.attrId = attrId;
        getAttr(attrId).then(res => {
          row.attrValOptions = res.data.sprdGoodsAttrValList;
          row.attrName = res.data.attrName;
          row.multiple = 'Y'===res.data.valueRadio;
        })
      }
    },
    /** 属性下拉列表修改事件 */
    handleAttrValChange(row, val) {
      if (row.multiple) {
        let values = val;
        let valueId = ''
        let valueName = ''
        if (values && values.length > 0) {
          values.filter(v => {
            valueId += v + ','
            let attrValOption = row.attrValOptions.find(o => o.valueId == v);
            if (attrValOption) {
              valueName += attrValOption.valueLabel + ', ';
            } else {
              valueName += v + ', ';
            }
          })
        }
        row.valueName = valueName.substring(0, valueName.length-2)
        row.valueId = valueId.substring(0, valueId.length-1)
      } else {
        let attrValOption = row.attrValOptions.find(o => o.valueId == val);
        if (attrValOption) {
          row.valueName = attrValOption.valueLabel;
        } else {
          row.valueName = val;
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedList = selection;
      this.config.indexs = selection.map(item => item.index);
      this.config.single = selection.length != 1;
      this.config.multiple = !selection.length;
    },
    /** dialog 属性列表 多选框选中数据 */
    handleAttrSelectionChange(selection) {
      this.dialogInfo.selectAttrList = selection;
    },
    /** 新增按钮 */
    handleConfigAdd() {
      const attrIds = this.configList.filter(item => item.attrId != null && item.attrId != undefined).map(item => item.attrId);
      const param = { 'gNumber': this.gNumber, 'attrIds': attrIds }
      findAttrsWithoutConfig(param).then(res => {
        this.dialogInfo.attrList = res.data;
        this.dialogInfo.configTitle = "新增商品属性"
        this.dialogInfo.configOpen = true;
      })
    },
    /** 新增一行按钮 */
    handleConfigAddLine() {
      const line = {
        gNumber: this.gNumber,
        valueId: null,
        delFlag: '0',
        attrValOptions: []
      }
      this.configList.push(line)
    },
    /** 删除所选行 按钮 */
    handleConfigDel() {
      if (this.selectedList.length == 0) {
        this.$modal.msgError("请先选择要删除的商品属性配置数据");
      } else {
        const configList = this.configList;
        const indexs = this.config.indexs;
        this.configList = configList.filter(item => indexs.indexOf(item.index) == -1);
      }
    },
    /** 属性表头自定义 */
    renderHeader(h, {column}) {
      let desc;
      if (column.label == '属性名称') {
        desc = '依据属性自动生成，不选择已有属性时，可自定义。'
      } else if (column.label == '属性值') {
        desc = '根据属性获取属性值列表，也可直接输入自定义属性值'
      } else if (column.label == '自定义属性值') {
        desc = '自定义属性，需要附加单位'
      }
      if (desc) {
        return [
          // 自定义图标
          <el-tooltip content={desc} placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>,
          // 自定义文本
          <span>&nbsp;{column.label}</span>
        ]
      } else {
        return null;
      }
    },
    /** 刷新商品属性配置 */
    handleRefreshConfig() {
      this.getConfigInfos();
    },
    /** 保存商品属性按钮 */
    handleSaveConfig() {
      console.log('configList: ', this.configList);
      this.configList.filter(c => {
        c.orderNum = c.index;
        if (c.valueIds) {
          c.valueIds = c.valueIds.sort();
          console.log(c.valueId, c.valueIds)
        }
      })
      const main = {
        gNumber: this.gNumber,
        sprdGoodsConfigList: this.configList
      }
      addConfig(main).then(()=> {
        this.$modal.msgSuccess("保存成功");
        this.handleRefreshConfig();
      })
    },
    /** 属性添加 dialog 添加按钮 */
    async handleAddAttr() {
      const selectAttrList = this.dialogInfo.selectAttrList;
      if (selectAttrList.length === 0) {
        this.$modal.msgError("请先选择要添加的商品属性");
      } else {
        this.config.loading = true;
        let list = []
        await this.generateConfigs().then(res => {
          list = res;
        })
        this.configList.push(...list);
        this.dialogInfo.configOpen = false;
        this.config.loading = false;
      }
    },
    // 根据选中的属性生成 配置信息
    async generateConfigs() {
      const selectAttrList = this.dialogInfo.selectAttrList;
      let list = [];
      for(let i = 0; i < selectAttrList.length; i++) {
        let attrValOptions = [];
        let attrName = null;
        let multiple = false;
        await getAttr(selectAttrList[i].attrId).then(r => {
          attrValOptions = r.data.sprdGoodsAttrValList;
          attrName = r.data.attrName;
          multiple = 'Y'==r.data.valueRadio
        })
        const line = {
          gNumber: this.gNumber,
          attrId: selectAttrList[i].attrId,
          attr: this.getCascaderVal(this.options.attrOptions, selectAttrList[i].attrId),
          attrName: attrName,
          valueId: null,
          delFlag: '0',
          attrValOptions: attrValOptions,
          multiple: multiple,
        }
        list.push(line);
      }
      return list;
    },
    // 查询图片信息
    getImgList() {
      this.image.loading = true;
      let params = {
        gNumber: this.gNumber,
        imgType: this.queryParams.imgType,
        delFlag: this.queryParams.delFlag,
      }
      listImg(this.queryParams).then(response => {
        // this.mainList = this.handleTree(response.data, "goodsId", "parentId");
        let list = response.rows;
        list.forEach(item => {
          if (this.isHttpUrl(item.imgPath)) {
            item.previewSrc = [ item.imgPath ]
          } else {
            item.previewSrc = [ this.image.imgServe + item.imgPath ]
          }
        })
        this.imageList = list;
        this.total = response.total;
        this.image.loading = false;
      });
    },
    /** a */
    handleImgSelectionChange(selection) {
      this.ids = selection.map(item => item.imgId)
      this.image.single = selection.length!==1
      this.image.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getImgList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetImage(orderNum) {
      this.image.form = {
        imageId: null,
        gNumber: this.gNumber,
        goodsName: this.mainInfo.goodsName,
        imgType: null,
        imgName: null,
        imgPath: null,
        orderNum: orderNum,
        delFlag: '0',
        remark: null,
      }
      this.resetForm("imageForm");
      if (this.$refs.uploadImage && this.$refs.uploadImage.$refs.imageUpload) {
        this.$refs.uploadImage.$refs.imageUpload.clearFiles(); // 清空已上传的文件列表
      }
    },
    /** 图片新增按钮操作 */
    async handleImageAdd() {
      let orderNum = 0;
      await findMaxOrderNum(this.gNumber).then(res => {
        orderNum = res.data;
      })
      this.resetImage(orderNum);
      this.dialogInfo.imageOpen = true;
      this.dialogInfo.imageTitle = "添加商品图片";
    },
    /** 图片修改按钮操作 */
    handleImageUpdate(row) {
      this.resetImage();
      const imgId = row.imgId || this.ids
      getImg(imgId).then(response => {
        let form = response.data;
        form.goodsCode = this.mainInfo.goodsCode,
          form.goodsName = this.mainInfo.goodsName,
          this.image.form = form;
        this.dialogInfo.imageOpen = true;
        this.dialogInfo.imageTitle = "修改商品图片";
      });
    },
    handleImageSuccess(fileList) {
      this.submitImageForm();
    },
    submitImageForm() {
      if (this.image.form.imgId != null) {
        updateImg(this.image.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.dialogInfo.imageOpen = false;
          this.getImgList();
        });
      } else {
        addImg(this.image.form).then(response => {
          this.$modal.msgSuccess("保存成功");
          this.dialogInfo.imageOpen = false;
          this.getImgList();
        });
      }
    },
    /** 图片提交按钮 */
    submitForm() {
      this.$refs["imageForm"].validate(async valid => {
        if (valid) {
          let params = {}
          if (!this.image.form.imgPath) {
            params.uploadFlag = '1';
            this.image.form.params = params;
            let files = this.$refs.uploadImage.$refs.imageUpload.uploadFiles; // 获取选中的文件列表
            if (files && files.length > 0) {
              this.$refs.uploadImage.$refs.imageUpload.submit(); // 手动调用上传
            } else {
              this.$modal.msgError("请先选择图片");
            }
          } else {
            params.uploadFlag = '';
            this.image.form.params = params;
            this.submitImageForm();
          }
        }
      });
    },
    // 取消按钮
    imageCancel() {
      this.dialogInfo.imageOpen = false;
      this.getImgList();
    },
    /** 图片删除按钮操作 */
    handleImageDelete(row) {
      const imgIds = row.imgId || this.ids;
      this.$modal.confirm('是否确认删除商品图片编号为"' + imgIds + '"的数据项？').then(function() {
        return delImg(imgIds);
      }).then(() => {
        this.getImgList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 上传图片数量 */
    uploadLimit(form) {
      if (form.imgId) {
        return 1;
      } else {
        return 5;
      }
    },
    /** 获取商品详情信息 */
    getDesc() {
      this.desc.loading = true;
      listDesc(this.gNumber).then(res => {
        this.descList = res.data;
      })
      this.desc.loading = false;
    },
    /** 刷新商品详情信息 */
    handleRefreshDesc() {
      this.getDesc();
    },
    /** 商品详情添加 */
    handleDescAdd() {
      this.resetDescForm();
      this.dialogInfo.descOpen = true;
      this.dialogInfo.descTitle = "添加商品详情描述";
    },
    /** 商品详情修改 */
    handleDescUpdate(row) {
      this.resetDescForm();
      const descId = row.descId
      getDesc(descId).then(res => {
        let form = res.data;
        this.desc.form = form;
        this.dialogInfo.descOpen = true;
        this.dialogInfo.descTitle = "修改商品详情描述";
      });
    },
    resetDescForm() {
      this.desc.form = {
        descId: null,
        gNumber: this.gNumber,
        content: null,
        delFlag: '0',
        remark: null,
      }
      this.resetForm("descForm");
    },
    /** 商品详情取消 */
    descCancel() {
      this.dialogInfo.descOpen = false;
      this.getDesc();
    },
    descSubmitForm() {
      const form = this.desc.form;
      console.log(form)
      if (form.descId != null) {
        updateDesc(form).then(()=> {
          this.dialogInfo.descOpen = false;
          this.$modal.msgSuccess("修改成功");
          this.handleRefreshDesc();
        })
      } else {
        addDesc(form).then(()=> {
          this.dialogInfo.descOpen = false;
          this.$modal.msgSuccess("保存成功");
          this.handleRefreshDesc();
        })
      }
    },
    /** 商品详情删除 */
    handleDescDelete(row) {
      if (row && row.descId) {
        const descId = row.descId;
        this.$modal.confirm('是否确认删除商品详情编号为"' + descId + '"的数据项？').then(function() {
          return delDesc(descId);
        }).then(() => {
          this.handleRefreshDesc();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 判断url是否以http开头 */
    isHttpUrl(url) {
      if (url) {
        return url.startsWith('http');
      }
      return false;
    },
    /** 打开授权用户表弹窗 */
    openSelectImage() {
      this.$refs.select.show();
    },
    /** 选择图片回调 */
    handleSelectOk(val) {
      if (val && val.length >= 1) {
        let path = '';
        let imageIds = '';
        for (let i = 0, len = val.length; i < len; i++) {
          if (val[i].imagePath) {
            path += val[i].imagePath + ',';
            imageIds += val[i].imageId + ',';
          }
        }
        if (path.slice(-1) === ',') {
          path = path.slice(0, -1);
        }
        if (imageIds.slice(-1) === ',') {
          imageIds = imageIds.slice(0, -1);
        }
        this.image.form.imageIds = imageIds;
        this.image.form.imgPath = path;
      }
    },
    handleGetAssConfig() {
      if (this.mainInfo.assNumber) {
        this.getConfigInfos(this.mainInfo.assNumber);
      }
    },
  }
}
</script>

<style scoped>
::v-deep .el-table .info-row {
  background: #f5f7fa;
  .el-table__cell {
    background: #f5f7fa !important;
  }
}
::v-deep .el-table .required {
  background: #f7f2f2;
  .el-table__cell {
    background: #f7f2f2 !important;
  }
}
::v-deep .el-descriptions {
  .el-descriptions-item__label {
    width: 100px;
  }
  .el-descriptions-item__content {
    width: 25vh;
  }
}
</style>
